/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.rpc;

import java.io.IOException;
import java.util.Collection;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import it.gashale.jacolib.core.ProtocolError;
import it.gashale.jacolib.json.SerializationObjectInterface;
import it.gashale.jacolib.json.Serializer;

public class RPCRequest implements SerializationObjectInterface {
	protected String method;
	protected Vector<Object> parameters;
		
	public RPCRequest() {
		method=null;
		parameters=new Vector<Object>();
	}
	public RPCRequest(String method) {
		this.method=method;
		parameters=new Vector<Object>();
	}
	
	public Vector<Object> getParameters() {
		return parameters;
	}
	public void addParameter(Object obj) {
		parameters.add(obj);
	}
	
	public void readObject(Serializer serializer, JSONObject jsonobj) throws JSONException, IOException, ProtocolError {
		method=jsonobj.getString("method");
		parameters.clear();
		Object p=jsonobj.get("params");
		if(p == JSONObject.NULL) {
		} else {
			JSONArray a=(JSONArray)p;
			for (int i=0; i<a.length(); ++i) {
				Object obj=a.get(i);
				if(obj.getClass().equals(JSONObject.class)) {
					obj=serializer.json_to_object((JSONObject)obj);
				}
				parameters.add(obj);
			}
		}
	}

	public void writeObject(Serializer serializer, JSONObject jsonobj) throws JSONException, IOException {
		jsonobj.put("type", "rpc.request");
		jsonobj.put("method", method);
		jsonobj.put("params", serializer.object_to_json((Collection)parameters));
	}
}
